//
//  QKChooseOneAlbum.m
//  fmb
//
//  Created by ChiCo on 2017/6/15.
//  Copyright © 2017年 Linktone. All rights reserved.
//

#import "QKChooseOneAlbum.h"
#import "QKEasyAlbumCell.h"
#import <Photos/Photos.h>
#import "QKEasyAlbumTopBar.h"

@interface QKChooseOneAlbum () <UICollectionViewDelegate,UICollectionViewDataSource,PHPhotoLibraryChangeObserver>


/**
 * chosed: YES 选择照片完成 NO 取消选择照片
 * assets: 选择的照片
 */
@property (nonatomic,copy)void (^finish)(BOOL chosed,PHAsset *assets);


/**
 * 可供展示的照片
 */
@property (nonatomic,strong)PHFetchResult *fetchResult;





@property (nonatomic,strong)UICollectionView *collectionView;


@end

@implementation QKChooseOneAlbum

/**
 * 选择相册
 * controller 当前控制器
 * assets: 选择的照片
 */
+ (QKChooseOneAlbum *)showAlblumWithController:(UIViewController *)controller
                                        finish:(void (^)(BOOL chosed,PHAsset *asset))finish
{
    QKChooseOneAlbum *album = [[QKChooseOneAlbum alloc] init];
    album.finish = finish;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:album];
    nav.navigationBarHidden = YES;
    [controller presentViewController:nav
                             animated:YES
                           completion:NULL];
    return album;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setUpSubViews];
    [self loadData];
    [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
}

- (void)photoLibraryDidChange:(PHChange *)changeInstance {
    //改变数据了,重新加载一下
    [self loadData];
    
}

- (void)loadData {
    
    //没有权限要申请权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        NSString *alerString = [NSString stringWithFormat:@"允许%@访问你的手机相册", appName];
        UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"使用相册" message:alerString preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        
        [aletController addAction:cancelAction];
        [aletController addAction:setAction];
        [self presentViewController:aletController animated:YES completion:^{
            
        }];
    }
    
    @weakify(self);
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus authorizationStatus) {
        @strongify(self);
        if (authorizationStatus == PHAuthorizationStatusAuthorized) {
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
            PHFetchResult *request = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
            self.fetchResult = request;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                NSUInteger count = [self.fetchResult count];
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:(NSInteger)count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
            });
        }
    }];
    
}

- (void)setUpSubViews {
    [self setupCollectionView];
    CGFloat topHeight = 44;
    if (KScreenHeight >= 812) topHeight = 78;
    QKEasyAlbumTopBar *topBar = [[QKEasyAlbumTopBar alloc] initWithFrame:CGRectMake(0, 0, KScreenHeight, topHeight)];
    [topBar.backButton addTarget:self
                          action:@selector(cacelAction)
                forControlEvents:UIControlEventTouchUpInside];
    [topBar.cancelButton addTarget:self
                            action:@selector(cacelAction)
                  forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBar];
    
    [topBar.titleLabel setText:@"相册胶卷"];
    
}

- (void)cacelAction {
    if (self.finish) {
        self.finish(NO, nil);
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)setupCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 2.5;
    layout.minimumInteritemSpacing = 2.5;
    CGFloat width = (KScreenHeight-12.5)/4;
    layout.itemSize = CGSizeMake(width, width);
    self.title = @"相册胶卷";
    CGFloat topHeight = 44;
    if (KScreenHeight >= 812) topHeight = 78;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(2.5, topHeight, KScreenWidth-5, KScreenHeight-topHeight) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    [self.collectionView registerClass:[QKEasyAlbumCell class] forCellWithReuseIdentifier:@"EasyAlbumCell"];
    [self.collectionView setBackgroundColor:[UIColor blackColor]];
    [self.view setBackgroundColor:[UIColor blackColor]];
    //滚动视图不需要全屏切换
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    // Fallback on earlier versions
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (NSInteger)[self.fetchResult count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    QKEasyAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EasyAlbumCell" forIndexPath:indexPath];
    cell.asset = [self.fetchResult objectAtIndex:(NSUInteger)indexPath.row];
    [cell hidenChooseImageView];
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    QKEasyAlbumCell *cell = (QKEasyAlbumCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (self.finish) {
        self.finish(YES, cell.asset);
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)dealloc {
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}
@end
